package git.soulbgm.tcp.client.common.socket;

import git.soulbgm.utils.ByteUtil;
import git.soulbgm.utils.LogUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-18 9:22
 * @description
 */
public class TcpClient implements Runnable {

    private LogUtil log = new LogUtil(getClass());

    private static final String TCP_DELIMITER = "$_$";

    /**
     * TCP客户端连接服务器的IP
     */
    private String tcpHost;
    /**
     * TCP客户端连接服务的端口
     */
    private int tcpPort;
    /**
     * TCP传输数据的线程数
     */
    private int tcpWorkerThreadNumber;

    /**
     * 管理传输数据线程组
     */
    private EventLoopGroup workGroup;

    /**
     * 传输管道
     */
    private Channel channel;

    private Bootstrap bootstrap;

    private ChannelInboundHandlerAdapter tcpClientHandle;

    public TcpClient(String tcpHost, int tcpPort) {
        this.tcpHost = tcpHost;
        this.tcpPort = tcpPort;
        this.tcpWorkerThreadNumber = 1;
    }

    public String getTcpHost() {
        return tcpHost;
    }

    public int getTcpPort() {
        return tcpPort;
    }

    /**
     * 开启TCP客户端
     *
     * @param tcpClientHandle TCP处理数据的handle
     */
    public void start(ChannelInboundHandlerAdapter tcpClientHandle) {
        this.tcpClientHandle = tcpClientHandle;
        Thread t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {
        workGroup = new NioEventLoopGroup(tcpWorkerThreadNumber);
        bootstrap = new Bootstrap()
                .group(workGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
                                /*
                                    第一个参数 60 表示读操作空闲时间
                                    第二个参数 20 表示写操作空闲时间
                                    第三个参数 60*10 表示读写操作空闲时间
                                    第四个参数 单位/秒
                                 */
//                                .addLast(new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS))
                                .addLast(new DelimiterBasedFrameDecoder(2048, ByteUtil.byteArrayToByteBuf(TCP_DELIMITER.getBytes())))
                                .addLast(tcpClientHandle)
                                .addLast(new StringEncoder());
                    }
                });
        doConnect();
    }

    public void doConnect() {
        /*if (channel != null && channel.isActive()) {
            return;
        }*/
        try {
            ChannelFuture future = bootstrap.connect(tcpHost, tcpPort);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        channel = future.channel();
                        log.info("ip:{}, port:{} tcp client start-up", tcpHost, tcpPort);
                    }
                }
            });
            channel = future.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("tcp client connect {}:{} fail", tcpHost, tcpPort, e);
        }
    }

    public void destroy() {
        channel.close();
        workGroup.shutdownGracefully().syncUninterruptibly();
        log.info("ip:{}, port:{} close tcp client success", tcpHost, tcpPort);
    }

    public static boolean sendMsg(Channel channel, byte[] data) {
        data = ByteUtil.byteMergerAll(data, TCP_DELIMITER.getBytes());
        if (channel != null) {
            channel.writeAndFlush(ByteUtil.byteArrayToByteBuf(data));
            return true;
        } else {
            return false;
        }
    }

}
